import jwt from "jsonwebtoken";
import EnvVars from "@src/declarations/major/EnvVars";
import moment from "moment";
// @ts-ignore
import SnowflakeId from "snowflake-id";

// 雪花id，参数为当前毫秒时间戳
export const getID = () => {
    const snowflake = new SnowflakeId({
        mid: EnvVars.workerId,
        offset: (parseInt(moment().format("YYYY")) - 1970) * 31536000 * 1000
    });
    return snowflake.generate().toString()
};


//生成token
export const getToken = (data: { id: string, username: string, password: string }) => {
    return jwt.sign(data, EnvVars.jwt.secret, {expiresIn: EnvVars.jwt.exp});
}
//解密token
export const getDecryptToken = (token: string): { token: boolean, data: any } => {
    try {
        const data = jwt.verify(token, EnvVars.jwt.secret);
        return {
            token: true,
            data
        }
    } catch (err) {
        return {
            token: false,
            data: null
        }
    }
};

//请求地址或者请求体参数验证
export const checkParams = (params: any, checkData: Array<string>) => {
    let flag = true;
    // 参数获取
    checkData.forEach((v: string) => {
        // 如果存在一个参数
        if (params[v] === undefined) {
            flag = false;
        }
    });
    return flag;
}

//克隆对象
export const clone = (obj: any) => JSON.parse(JSON.stringify(obj));

//分页计算
export const getMeta = (total: number, currentPage: number, perSize: number) => {
    return {
        // 总条数
        total,
        // 每页条数
        perSize,
        // 最后一页
        lastPage: Math.ceil(total / perSize),
        //当前页
        currentPage
    }
}

//等待一定的时间
export const tick = (time: number): Promise<void> => {
    return new Promise(resolve=>{
        setTimeout(()=>{
            resolve
        },time)
    })
}